package com.artPreter.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class PinyinUtil {

    public static String getPinyin(String chinese) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        StringBuilder pinyin = new StringBuilder();
        char[] chars = chinese.toCharArray();
        for (char c : chars) {
            if (Character.isWhitespace(c)) {
                continue; // 忽略空格
            }
            try {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                System.out.println(pinyinArray[0] + "拼音");
                if (pinyinArray!= null && pinyinArray.length > 0) {
                    // 多音字
                    if(c=='曾'){
                        pinyinArray[0] = "zeng";
                    }
                    if(c=='长'){
                        pinyinArray[0] = "chang";
                    }
                    pinyin.append(pinyinArray[0]).append(" "); // 只取第一个拼音，并添加空格
                } else {
                    pinyin.append(c); // 如果无法转换，直接添加原字符
                }
            } catch (Exception e) {
                pinyin.append(c); // 如果发生异常，直接添加原字符
            }
        }
        String result = pinyin.toString().trim();
        return result; // 去除末尾的空格
    }

}

